<?php
namespace app\common\controller;
use OSS\OssClient;

/**
 * 微信小程序类
 * Created by PhpStorm.
 * User: tyll
 * Date: 2020/03/11
 * Time: 13:24
 */
class WxMini{

    /**
     * 生成小程序码
     * @param $scene
     * @return int|string
     */
    public function gen_mini_code($scene){
         $maps = [];
         $maps[] = ['key','in',['access_token']];
         $conf_info = model('conf')->get_list($maps);
         $conf_info_new = [];
         foreach ($conf_info as $k => $v) {
             $conf_info_new[$v['key']] = $v['value'];
         }

         $access_token_arr = json_decode($conf_info_new['access_token'],true);

         $tools = new Tools();
         $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $access_token_arr['access_token'];

         $post_data['scene'] = $scene;
         $post_data['page'] = 'pages/patrol-shop/patrol-space/patrol_space';
         $r_json = $tools->PostuseCurl($url,json_encode($post_data));
         $r_obj = json_decode($r_json);
         if(!empty($r_obj) && property_exists($r_obj,'errcode')){
             return 0;
         }

        $accessKeyId = 'LTAI4Fm7FCnjThvu6oneb4Uj';
        $accessKeySecret = 'UxIMArmlsyXFVeiE2FAijJAxth3kV8';

        $endpoint = 'http://oss-cn-zhangjiakou.aliyuncs.com/';

        $bucket = 'mdxundian';

        $object = 'xcx_code/upload_' . date('YmdHis') . mt_rand(1000,9999) . '.jpg';

        $content = $r_json;

        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $r = $ossClient->putObject($bucket, $object, $content);
            if(isset($r['info'])){
                $url = $r['info']['url'];
                $url = str_replace('http','https',$url);
                return $url;
            }
            return 0;
        } catch(OssException $e) {
            //printf(__FUNCTION__ . ": FAILED\n");
            //printf($e->getMessage() . "\n");
            return 0 ;
        }
        //print(__FUNCTION__ . ": OK" . "\n");
        return 0 ;
    }
}